package com.learning.servlet2x.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * ClassName: CharacterEncodingFilter
 * Description: 编码过滤器
 * 1、Spring 就实现了自己的 编码Filter，直接参考即可
 * <p>
 * Date: 2014-10-12 21:16 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class CharacterEncodingFilter implements Filter {

    private String characterEncoding;
    /**
     * 是否启用
     */
    private boolean enabled;

    @Override
    public void init(FilterConfig config) throws ServletException {

        // 获取配置好的参数，
        // 配置好的字符编码
        characterEncoding = config.getInitParameter("characterEncoding");
        //是否启用
        enabled = "true".equalsIgnoreCase(config.getInitParameter("enabled"));
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //设置字符编码
        if (enabled && characterEncoding != null) {
            request.setCharacterEncoding(characterEncoding);
            response.setCharacterEncoding(characterEncoding);
        }
        //调用下一个过滤器
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        //注销的时候，设为空
        characterEncoding = null;
    }
}
